package com.jeesite.modules.pay.totalPay.restController;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.cache.CacheUtils;
import com.jeesite.common.responseReturn.entity.ResultObject;
import com.jeesite.common.responseReturn.web.Render;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.config.MyProps;
import com.jeesite.modules.goods.entity.ZtCard;
import com.jeesite.modules.goods.entity.ZtCardMem;
import com.jeesite.modules.goods.entity.ZtCardOrder;
import com.jeesite.modules.goods.entity.ZtColor;
import com.jeesite.modules.goods.entity.ZtFinancial;
import com.jeesite.modules.goods.entity.ZtGoods;
import com.jeesite.modules.goods.entity.ZtGoodsOrder;
import com.jeesite.modules.goods.entity.ZtOrder;
import com.jeesite.modules.goods.entity.ZtQuan;
import com.jeesite.modules.goods.entity.ZtQuanself;
import com.jeesite.modules.goods.entity.ZtSpecifications;
import com.jeesite.modules.goods.entity.ZtTrolley;
import com.jeesite.modules.goods.service.ZtAddrService;
import com.jeesite.modules.goods.service.ZtCardMemService;
import com.jeesite.modules.goods.service.ZtCardOrderService;
import com.jeesite.modules.goods.service.ZtColorService;
import com.jeesite.modules.goods.service.ZtFinancialService;
import com.jeesite.modules.goods.service.ZtGoodsOrderService;
import com.jeesite.modules.goods.service.ZtGoodsService;
import com.jeesite.modules.goods.service.ZtOrderService;
import com.jeesite.modules.goods.service.ZtQuanService;
import com.jeesite.modules.goods.service.ZtQuanselfService;
import com.jeesite.modules.goods.service.ZtSpecificationsService;
import com.jeesite.modules.goods.service.ZtTrolleyService;
import com.jeesite.modules.pay.totalPay.service.NativePayService;
import com.jeesite.modules.pay.totalPay.util.HttpXmlUtils;
import com.jeesite.modules.pay.totalPay.util.WxSignUtils;
import com.jeesite.modules.pay.wxpay.api.ConstantUtil;
import com.jeesite.modules.pay.wxpay.api.UUID;
import com.jeesite.modules.xcxAdmin.entity.ZtAdmin;
import com.jeesite.modules.xcxAdmin.service.ZtAdminService;

/**
 * 
 * @author tz
 * @category 支付入口 controller <br>
 * @version 1.0 <br>
 * 
 *          2017-9-13 19:58:35<br>
 *          nativePay为目前两种支付的入口，其他参数可反编译jar 重新抒写加入<br>
 * 
 * 
 * 
 *          原生支付：http://localhost:8888/interface/native/nativePay/1||2
 *          H5支付：http://localhost:8888/tz/H5
 * 
 * 
 *          微信H5支付的时候获取ip地址是客户端的ip地址，后面唤起微信支付的也是需要与客户端的ip地址对应，不然会出现，具体看官网文档。
 *          其次微信H5支付的成功返回页面在得到支付请求时的地址后追加URL编码，具体看官网文档。
 */

@Controller
@RequestMapping(value = "${frontPath}/interface/card")
public class CardPayController extends BaseController {

	protected static Logger logger = LoggerFactory
			.getLogger(NativePayController.class);

	private String pay_title = "微沃";
	private String orderNo = "";// 订单号

	private String openid;
	
	@Autowired
	ZtFinancialService ztFinancialService;

	@Autowired
	private ZtAdminService ztAdminService;
	
	@Autowired
	private ZtCardOrderService ztCardOrderService;

	@Autowired  
    private MyProps myProps;

	@Autowired
	private ZtCardMemService ztCardMemService;
	/**
	 * 原生App支付 service 1微信 2 支付宝 3 h5微信 4 h5支付宝 5 微信扫码 6支付宝扫码
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "pay")
	public void cardPay(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		Map<String, String> putMap = new HashMap<String, String>();
		ResultObject res = new ResultObject();
		String paramStr = getParams(request);
		JSONObject jo = JSONObject.parseObject(paramStr);
		ZtCardOrder ztCardOrder = new ZtCardOrder();
		pay_title = "企购购商城";
		
		openid = jo.getString("openid");
		boolean isOrderTemp=false;
		if(jo.get("orderNo")!=null){
			if(!"null".equals(orderNo)&&!"undefined".equals(orderNo)){
			isOrderTemp=true;
			orderNo = jo.get("orderNo").toString();
			}
		}else{
			orderNo = String.valueOf(UUID.next());
		}

		String price = jo.getString("price").toString();//  合计总价
		Double balance=0D;
		if(jo.get("balance")!=null){
			if(StringUtils.isNotBlank(jo.get("balance").toString())){
				balance = Double.valueOf(jo.get("balance").toString());
			}else{
				balance=0D;
			}
		}
		
		String adminid = jo.getString("adminid").toString();// 小程序用户id
		
		String cardid = jo.getString("cardid").toString();
		ZtCard ztCard = new ZtCard();
		ztCard.setId(cardid);
		Date date = new Date();
		
		ztCardOrder.setPrice(Double.valueOf(price));//合计总价
		ztCardOrder.setBalance(balance);//余额
		
		
		ZtAdmin ztAdmin = new ZtAdmin();
		ztAdmin.setId(adminid);
		ztCardOrder.setZtAdmin(ztAdmin);
		ztCardOrder.setCreateDate(date);
		ztCardOrder.setOrderTime(date);

		ztCardOrder.setOrderstatus("0");
		ztCardOrder.setZtCard(ztCard);
		ztCardOrder.setOrder(orderNo);
		
		if(!isOrderTemp){
			ztCardOrderService.save(ztCardOrder);
		}
		
		long dateTime = System.currentTimeMillis();

		Map<String, String> result = new HashMap<String, String>();
		putMap.put("pay_title", pay_title.trim());// 支付标题

		String spbill_create_ip = "";// getIpAddr_client
		try {

			spbill_create_ip = com.jeesite.modules.pay.totalPay.util.StringUtil
					.getIpAddr_client(request);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 控制器调用的时候填入，jar里面会自动填入微信
		putMap.put("total_fee",
				String.valueOf((int) (Double.valueOf(price) * 100)).trim());// 金额
		// 都是以分单位，支付宝传入的时候会自动变成分单位

		Map<String, String> nativePay = new HashMap<>();

		// 微信H5
		putMap.put("out_trade_no", orderNo.trim());
		putMap.put("openid", openid.trim());
		putMap.put("notify_url", ConstantUtil.NOTIFY_CARD_URL.trim());// 回调地址
		putMap.put("spbill_create_ip", spbill_create_ip.trim()); // 终端ip 微信支付需要
		// 支付宝不需要

		nativePay = NativePayService.weixinH5pay(putMap);
		nativePay.put("orderid", ztCardOrder.getId());


		
		res.setResult(200L);
		res.setData(nativePay);
		Render.renderString(response, res);

	}

	/**
	 * 微信异步回调
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "card_notiyReturn")
	public String card_notiyReturn(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		// 读取参数
		InputStream inputStream;
		
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(
				inputStream, "UTF-8"));
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		in.close();
		inputStream.close();

		Map return_data = new HashMap();

		// 解析xml成map
		Map m = new HashMap();
		m = HttpXmlUtils.doXMLParse(sb.toString());

		// 过滤空 设置 TreeMap
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		Iterator it = m.keySet().iterator();
		while (it.hasNext()) {
			String parameter = (String) it.next();
			String parameterValue = (String) m.get(parameter);

			String v = "";
			if (null != parameterValue) {
				v = parameterValue.trim();
			}
			packageParams.put(parameter, v);
		}

		String code = "";
		String msg = "";

		// 判断签名是否正确
		if (WxSignUtils.isWxPaySign("UTF-8", packageParams)) {
			// ------------------------------
			// 处理业务开始

			// ------------------------------
			String resXml = "";
			if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
				// 支付成功
				Date da=new Date();

				String out_trade_no = (String) packageParams
						.get("out_trade_no");
				
				ZtCardOrder ztCardOrder = new ZtCardOrder();

				ztCardOrder.setOrder(out_trade_no);
				ztCardOrder = ztCardOrderService.getByOrder(ztCardOrder);
				if(ztCardOrder==null){
					return_data.put("return_code", "SUCCESS");
					return_data.put("return_msg", "OK");
					return HttpXmlUtils.GetMapToXML(return_data);
				}
				
				ZtAdmin ztAdmin=ztAdminService.get(ztCardOrder.getZtAdmin().getId());
				if(ztAdmin==null){
					return_data.put("return_code", "SUCCESS");
					return_data.put("return_msg", "OK");
					return HttpXmlUtils.GetMapToXML(return_data);
				}
				
				// 更新用户的付费状态和时间
				ztCardOrder.setPayTime(da);
				
				ztCardOrder.setOrderstatus("1");
				ztCardOrderService.save(ztCardOrder);//更新支付状态	
				
				//更改用户为会员
				ztAdmin.setMemtype("1");
				if(StringUtils.isNotBlank(ztAdmin.getLastadmin())){
					if("0".equals(ztAdmin.getLevel())){
						ztAdmin.setLevel("1");
					}
				}
				ztAdminService.save(ztAdmin);
				
				//会员信息
				ZtCardMem ztCardMem=new ZtCardMem();
				ztCardMem.setAdminid(ztAdmin.getId());
				ztCardMem.setCardid(ztCardOrder.getZtCard().getId());
				ztCardMem.setStartDate(da);
				ztCardMem.setEndDate(DateUtils.addYears(da, 1));
				ztCardMem.setCreateDate(da);
				
				
				ZtCardMem zm=ztCardMemService.getByAdminid(ztCardMem);
				if(zm!=null){
					zm.setStartDate(da);
					zm.setEndDate(DateUtils.addYears(da, 1));
					zm.setCreateDate(da);
					ztCardMemService.save(zm);
				}else{
					ztCardMemService.save(ztCardMem);
				}
				
				//分佣
				forFinancial(ztCardOrder,ztAdmin,da);
					
				}
					
				return_data.put("return_code", "SUCCESS");
				return_data.put("return_msg", "OK");

			} else {

				return_data.put("return_code", "FAIL");
				return_data.put("return_msg", "签名错误");
			}

		

		return HttpXmlUtils.GetMapToXML(return_data);

	}

	
	
	
	public String getParams(HttpServletRequest request) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					(ServletInputStream) request.getInputStream()));
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			String appMsg = sb.toString();
			return appMsg;
		} catch (Exception ex) {
			ex.printStackTrace();

		}
		return "";
	}
	
	public void forFinancial(ZtCardOrder ztCardOrder,ZtAdmin ztAdmin,Date da){
		ZtCard ztCard=ztCardOrder.getZtCard();
		String lastadminid=ztAdmin.getLastadmin();
		
		if(StringUtils.isNotBlank(lastadminid)){//有上级
			ZtAdmin	lastadmin=getLastLevelAdmin(ztAdmin);
			
			
			/**一级返佣******START********/
			/*ZtAdmin lastadmin=new ZtAdmin();
			lastadmin.setId(lastadminid);
			lastadmin=ztAdminService.get(lastadmin);*/
			
			if(lastadmin==null || StringUtils.isBlank(lastadmin.getId())){
				return;
			}
			
			String level=lastadmin.getLevel();
			double priceCard=0D;
			if("0".equals(level)){
				
			}else if("1".equals(level)){
				priceCard=ztCard.getCopperOnePriceCard();
			}else if("2".equals(level)){
				priceCard=ztCard.getSilverOnePriceCard();
			}else if("3".equals(level)){
				priceCard=ztCard.getGoldOnePriceCard();
			}
			
			lastadmin.setAmount((lastadmin.getAmount()==null?0:lastadmin.getAmount())+priceCard);
			lastadmin.setCashAmount((lastadmin.getCashAmount()==null?0:lastadmin.getCashAmount())+priceCard);
			ztAdminService.save(lastadmin);
			
			ZtFinancial ztFinancial=new ZtFinancial();
			ztFinancial.setType("1");
			ztFinancial.setContent("会员订单-成为会员");
			ztFinancial.setZtAdmin(lastadmin);
			ztFinancial.setPricestr("+￥"+priceCard);
			ztFinancial.setPrice(priceCard);
			ztFinancial.setCreateDate(da);
			ztFinancial.setUsername("(粉丝)"+ztAdmin.getUsername());
			ztFinancial.setHeadimgurl(ztAdmin.getHeadimgurl());
			ztAdminService.setNames();
			ztFinancialService.save(ztFinancial);
			/**一级返佣******END********/
			
			//String lastTwoadminid=lastadmin.getLastadmin();
			
			ZtAdmin	lastTwoadmin=getLastLevelAdmin(lastadmin);
			
			if(lastTwoadmin==null || StringUtils.isBlank(lastTwoadmin.getId())){
				return;
			}
			
			if(StringUtils.isNotBlank(lastTwoadmin.getId())){//有上级
				/**二级返佣******START********/
				
				 level=lastTwoadmin.getLevel();
				 priceCard=0D;
				if("0".equals(level)){
					
				}else if("1".equals(level)){
					priceCard=ztCard.getCopperTwoPriceCard();
				}else if("2".equals(level)){
					priceCard=ztCard.getSilverTwoPriceCard();
				}else if("3".equals(level)){
					priceCard=ztCard.getGoldTwoPriceCard();
				}
				
				lastTwoadmin.setAmount((lastTwoadmin.getAmount()==null?0:lastTwoadmin.getAmount())+priceCard);
				lastTwoadmin.setCashAmount((lastTwoadmin.getCashAmount()==null?0:lastTwoadmin.getCashAmount())+priceCard);
				ztAdminService.save(lastTwoadmin);
				
				ZtFinancial ztFinancial2=new ZtFinancial();
				ztFinancial2.setType("2");
				ztFinancial2.setContent("会员订单-成为会员");
				ztFinancial2.setZtAdmin(lastTwoadmin);
				ztFinancial2.setPricestr("+￥"+priceCard);
				ztFinancial2.setPrice(priceCard);
				ztFinancial2.setCreateDate(da);
				ztFinancial2.setUsername(lastadmin.getUsername());
				ztFinancial2.setHeadimgurl(lastadmin.getHeadimgurl());
				ztAdminService.setNames();
				ztFinancialService.save(ztFinancial2);
				/**二级返佣******END********/
			}
			
		}
	}
	
	
	public ZtAdmin getLastLevelAdmin(ZtAdmin ztAdmin){
		 ZtAdmin lastadmin=new ZtAdmin();
		 if(ztAdmin !=null && StringUtils.isNotBlank(ztAdmin.getLastadmin())){
			lastadmin.setId(ztAdmin.getLastadmin());
			lastadmin=ztAdminService.get(lastadmin);
			if(lastadmin!=null && StringUtils.isNotBlank(lastadmin.getId())){
				
				if(!"0".equals(lastadmin.getLevel())){
					return lastadmin; 
				}else{
					getLastLevelAdmin(lastadmin);
				}
				
			}else{
				
				return lastadmin;
			}
		 }
			return lastadmin;
	 }
}
